package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"novel-sys/cache"
	"novel-sys/model/mysql"
	"time"

	"novel-sys/goods/goods"
	"novel-sys/goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CommentListLogic) CommentList(in *goods.CommentListRequest) (*goods.CommentListResponse, error) {
	// todo: add your logic here and delete this line
	var novel mysql.Novel
	data := novel.NoveBycomment(mysql.DB, in.NovelId)
	var comment []*goods.CommentList
	key := fmt.Sprintf("commentList%d", in.NovelId)
	cachedata, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cachedata == "" {
		comment = mysql.CommentList(mysql.DB, in.NovelId)
		mar, _ := json.Marshal(comment)
		cache.Rdb.Set(l.ctx, key, mar, time.Minute*3)
	} else {
		json.Unmarshal([]byte(cachedata), &comment)
	}

	return &goods.CommentListResponse{
		Title:     data.Title,
		Category:  data.Category,
		Label:     data.Label,
		Info:      data.Info,
		HeadImage: data.HeadImage,
		NickName:  data.NickName,
		List:      comment,
	}, nil
}
